package com.sense.kukoo.biz_explore.view

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.tabs.TabLayoutMediator
import com.sense.kukoo.biz_explore.R
import com.sense.kukoo.biz_explore.databinding.BizExploreFragmentExplore2Binding
import com.sense.kukoo.biz_explore.vm.Explore2ViewModel
import com.sense.kukoo.common.anim.TopTabAnimHelper
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.event.LoginSuccessEvent
import com.sense.kukoo.common.event.LogoutEvent
import com.sense.kukoo.common.event.MessageCountChangedEvent
import com.sense.kukoo.common.event.TabChangedEvent
import com.sense.kukoo.common.listener.OnScrollYChangedListener
import com.sense.kukoo.common.mvvm.view.BaseMvvmFragment
import com.sense.kukoo.common.repo.http.bean.ModuleBean
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.common.wiget.adapter.CommonPagerAdapter
import com.sense.kukoo.common.wiget.dialog.BottomLoginDialog
import com.sense.kukoo.common.wiget.state.NetworkErrorState
import com.sense.kukoo.common_i18n.I18n
import com.sense.kukoo.lib_logger.LoggerManager
import com.zy.multistatepage.state.SuccessState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * A simple [Fragment] subclass.
 * Use the [Explore2Fragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class Explore2Fragment : BaseMvvmFragment<Explore2ViewModel, BizExploreFragmentExplore2Binding>() {

    private val TAG: String = javaClass.simpleName

    private lateinit var mFragments:ArrayList<Fragment>
    private lateinit var mAdapter:CommonPagerAdapter

    private val mTopTabAnimHelper = TopTabAnimHelper()

    companion object {
        @JvmStatic
        fun newInstance() = Explore2Fragment()
    }

    override fun initParam() {}

    override fun responseVM(action: Int) {}

    override fun getLayout(): Int = R.layout.biz_explore_fragment_explore2

    override fun getViewModelClass(): Class<Explore2ViewModel> = Explore2ViewModel::class.java

    override fun initData() {
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        //
        mBinding.btn.setOnClickListener(object :View.OnClickListener{
            override fun onClick(p0: View?) {
                ARouter.getInstance()
                    .build(ARouterUrl.ROUTE_EXPLORE_MODULE_SEARCH1_ACTIVITY)
                    .navigation()
            }

        })
        bindAction(mViewModel.action_toSearch){
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_EXPLORE_MODULE_SEARCH_ACTIVITY)
                .navigation()
        }
        bindAction(mViewModel.action_toNotification){
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MESSAGES_MODULE_MESSAGES_ACTIVITY)
                .navigation()
        }
        bindAction(mViewModel.action_networkError){
            mBinding.multiStateContainer.show<NetworkErrorState> {
                it.onRetry {
                    mViewModel.getIndex()
                }
            }
        }
        bindAction(mViewModel.action_showLoginDialog){
            context?.let {
                BottomLoginDialog.autoShow(it)
            }
        }
        bindAction(mViewModel.action_showTopTab){
            mTopTabAnimHelper.animateToShow()
        }
        bindData(mViewModel.data_index){
            mBinding.multiStateContainer.show<SuccessState>()
            initNav(it)
        }
        bindData(mViewModel.data_messageCount){
            setNotificationNum(it)
        }
    }

    override fun initView() {
        mBinding.topTabs.setOnTabListener{
            EventBus.getDefault().post(TabChangedEvent(0, it))
        }
        initTopTab()
    }

    override fun singleLazyLoad() {
        mViewModel.initData()
    }

    private var mOnScrollYChangedListener: OnScrollYChangedListener? = null

    fun setOnScrollYChangedListener(l: OnScrollYChangedListener){
        mOnScrollYChangedListener = l
    }

    private val mContentListener = object : OnScrollYChangedListener {
        override fun onChanged(mainPosition: Int, explorePosition: Int, dy: Int, scrollState:Int) {
            //LoggerManager.e(TAG, "mainPosition=${mainPosition}, explorePosition=${explorePosition}, dy=${dy}")
            //
            mTopTabAnimHelper.dispatchScrollEvent(dy, scrollState)
            //
            mOnScrollYChangedListener?.onChanged(0, explorePosition, dy, scrollState)
        }
    }

    fun initTopTab(){
        mTopTabAnimHelper.setTabView(mBinding.topTabs)
        //
        mBinding.topTabs.alpha = 0F
        mBinding.topTabs.animate()
            .alpha(1F)
            .setDuration(400L)
            .withEndAction {
                val minTranslationY = -mBinding.topTabs.height.toFloat()
                mTopTabAnimHelper.setMinTranslationY(minTranslationY)
                LoggerManager.d(TAG, "minTranslationY=${minTranslationY}")
            }
            .start()
    }

    fun initNav(navMenus:List<ModuleBean>){
        mFragments = arrayListOf<Fragment>()
        var explorePosition = 0
        navMenus.forEach {
            val fragment = Content2Fragment.newInstance(it)
            fragment.setOnScrollYChangedListener(explorePosition, mContentListener)
            mFragments.add(fragment)
            explorePosition++
        }
        mAdapter = CommonPagerAdapter(activity as FragmentActivity, mFragments)
        //
        mBinding.viewPager.adapter = mAdapter
        mBinding.viewPager.isUserInputEnabled = true
        //
        val arrayTabStrings = arrayOfNulls<String>(navMenus.size)
        val localType = I18n.getLocalType(ApplicationContext.instance())
        navMenus.forEachIndexed {i, menu->
            when (localType) {
                I18n.TYPE_CHINESE -> {
                    arrayTabStrings.set(i, menu.nameCn)
                }
                I18n.TYPE_ENGLISH -> {
                    arrayTabStrings.set(i, menu.nameUs)
                }
                else -> {
                    arrayTabStrings.set(i, menu.nameTh)
                }
            }
        }
        mBinding.topTabs.init(arrayTabStrings)
        TabLayoutMediator(mBinding.topTabs, mBinding.viewPager) { tab, position ->
            mBinding.topTabs.setTab(tab, position)
        }.attach()
    }

    fun setNotificationNum(num: Int){
        if(num > 0){
            mBinding.llNumberNotification.visibility = View.VISIBLE
            mBinding.tvNumberNotification.text = "${num}"
        } else {
            mBinding.llNumberNotification.visibility = View.INVISIBLE
        }
    }

}